import 'package:flutter/material.dart';
import 'package:flutter_application_1/components/hide_scroll_shadow/hide_scroll_shadow.dart';

class Marquee extends StatefulWidget {
  final Widget child;
  final Duration duration;

  Marquee({
    Key? key,
    required this.child,
    this.duration = const Duration(seconds: 10),
  }) : super(key: key);

  @override
  _MarqueeState createState() => _MarqueeState();
}

class _MarqueeState extends State<Marquee> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation _animation;

  double _originWidth = 0;

  double _maxScrollExtent = 0;

  GlobalKey _key = GlobalKey();

  ScrollController _listController = ScrollController();

  double _getListWidth() {
    RenderObject? renderObject = _key.currentContext!.findRenderObject();
    Rect rect = renderObject!.semanticBounds;
    return rect.width;
  }

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      vsync: this,
      duration: widget.duration,
    );

    _animation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(
      CurvedAnimation(
        curve: Curves.linear,
        parent: _controller,
      ),
    );

    _animation.addListener(() {
      _listController.jumpTo(_maxScrollExtent * _animation.value);
    });

    WidgetsBinding.instance!.addPostFrameCallback((_) {
      setState(() {
        _originWidth = _getListWidth();
      });

      WidgetsBinding.instance!.addPostFrameCallback((_) {
        setState(() {
          _maxScrollExtent = _listController.position.maxScrollExtent;
        });

        _controller.repeat();
      });
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    _listController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.maxFinite,
      child: HideScrollShadow(
        child: SingleChildScrollView(
          key: _key,
          scrollDirection: Axis.horizontal,
          controller: _listController,
          physics: NeverScrollableScrollPhysics(),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(width: _originWidth),
              widget.child,
              SizedBox(width: _originWidth),
            ],
          ),
        ),
      ),
    );
  }
}
